package wangjg.codec.amr;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class AmrExtracter {
	public static final byte[] AMR_HEADER={0x23,0x21,0x41,0x4D,0x52,0x0A};
	private InputStream is;
	
	private static int[] bitrates = {4750, 5150, 5900, 6700, 7400, 7950, 1020, 12200};
	
	public byte[] readFileHeader() throws IOException{
		byte[] buf = new byte[6];
		is.read(buf);
		printHexString(buf);
		return buf;
	}
	
	public int getFrameByteCount(int ft){
		double bits = bitrates[ft]/50;
		double bytes = bits/8;
		return (int) Math.round(bytes);
	}
	
	public FrameHeader readFrameHeader() throws IOException{
		byte b = (byte)is.read();
		FrameHeader frameHeader = new FrameHeader();
		frameHeader.setP((b & Integer.parseInt ("10000000", 2))>>7);
		frameHeader.setFT((b & Integer.parseInt("01111000", 2))>>3);
		frameHeader.setQ((b & Integer.parseInt ("00000100", 2))>>2);
		return frameHeader;
	}
	
	public int nextFrame(byte[] buf) throws IOException{
		int n = is.read(buf);
		return n;
	}
	
	//将指定byte数组以16进制的形式打印到控制台  
	void printHexString( byte[] buf) {
	   for (int i = 0; i < buf.length; i++) {
		   String s = Integer.toHexString(buf[i]);
		   if(s.length()==1)
			   s="0"+s;
		   else if(s.length()>2)
			   s=s.substring(s.length()-2);
		   System.out.print(" "+s.toUpperCase());
	   }   
	   System.out.println();
	}
	
	public void setInputStream(InputStream is) {
		this.is = is;
	}

	public static void main(String args[]) throws Exception{
		String path="D:\\temp\\luyin.amr";
		FileInputStream fis = new FileInputStream(path);
		AmrExtracter ae = new AmrExtracter();
		ae.setInputStream(fis);
		ae.readFileHeader();

		FrameHeader firsth = ae.readFrameHeader();
		int frameSize = ae.getFrameByteCount(firsth.getFT());
		byte[] buf = new byte[frameSize];
		ae.nextFrame(buf);

		
		while(true){
			FrameHeader fh = ae.readFrameHeader();
			if(fh==null){
				break;
			}
			System.out.println( fh);
			
			int n = ae.nextFrame(buf);
			if(n<frameSize){
				System.out.println("frameSize="+frameSize+",n="+n);
				break;
			}
//			ae.printHexString(buf);
		}
	}
	
}
